package cn.parus.common.Execption;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public Result<String> handleCustomException(CustomException e) {
        log.error("业务异常: {}", e.getMsg());
        return Result.error(e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationException(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("参数校验失败: {}", errorMsg);
        return Result.error(errorMsg).addExtra("errorType", "VALIDATION_ERROR");
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage());
        return Result.error("系统繁忙，请稍后再试").addExtra("errorType", "SYSTEM_ERROR");
    }
}
